<?php

namespace App\Http\Controllers\Api;

use Backup;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Storage;

class BackupController extends BaseController
{
    public $user;
    //
    public function __construct(Request $request)
    {
        parent::__construct();
        $this->user = $this->is_login($request);
    }

    public function backup(Request $request){

        if (!$this->user['data']->can('backup_download')){
            return error('NoPermission');
        }

        $name = $request->input('name');
        if ($name){
            if(Backup::export($name)){
                return success('','备份成功');
            }else{
                return error('备份失败');
            }
        }else{
            if (Backup::export()){
                return success('','备份成功');
            }else{
                return error('备份失败');
            }
        }


    }

    public function restore(Request $request){

        if (!$this->user['data']->can('backup_download')) {
            return error('NoPermission');
        }

        if (!$name = $request->input('name')){
            return error('备份文件名缺失');
        }
        if (!in_array($name,$this->file_names())){
            return error('备份文件不存在');
        }
        $path = Backup::getPath();
        if (Backup::restore($path.'/'.$name)){
            return success('','数据恢复成功');
        }else{
            return error('数据恢复失败');
        }
    }

    public function get_list(Request $request){

        if (!$this->user['data']->can('backup_download')) {
            return error('NoPermission');
        }

        $list = $this->file_names();

        return success(array_reverse($list),'查询成功');
    }

    public function download_file(Request $request){

        if (!$this->user['data']->can('backup_download')) {
            return error('NoPermission');
        }

        if (!$file_path = $request->file_path){
            return error('文件路径缺失');
        }
        $path = Backup::getPath();
        $file_path = $path.'/'.$file_path;
        return response()->download($file_path);
    }

    public function file_names(){

        if (!$this->user['data']->can('backup_download')) {
            return error('NoPermission');
        }

        $path = Backup::getPath();
        $list = Backup::getRestorationFiles();
        $data = [];
        $length = strlen($path);
        foreach ($list as $item) {
            $data[] = substr($item,$length+1);
        }
        return $data;
    }
}
